package com.ug.managent.listener;

import com.rabbitmq.client.Channel;
import com.ug.common.config.RuoYiConfig;
import com.ug.common.utils.ProcessUtils;
import com.ug.managent.domain.Cover;
import com.ug.managent.domain.WorkOrder;
import com.ug.managent.mapper.CoverMapper;
import com.ug.managent.mapper.WorkOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.ug.common.utils.Threads.sleep;

@Component
@Slf4j
public class CoverListener {
    public static final String EXCHANGE_DIRECT = "exchange.direct.cover";
    public static final String ROUTING_KEY = "cover";
    public static final String QUEUE_NAME = "queue.cover";

    ExecutorService TASK_SERVICE = Executors.newFixedThreadPool(10);

    @Autowired
    private WorkOrderMapper workOrderMapper;

    @Autowired
    private CoverMapper coverMapper;

    @RabbitListener(queues = QUEUE_NAME)
    public void processMessage(String dataString, Message message, Channel channel) throws Exception {
        try{
            handleMessage(dataString);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            Boolean redelivered = message.getMessageProperties().getRedelivered();

            if(redelivered){
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
            throw new RuntimeException(e);
        }
    }

    private void handleMessage(String dataString) {
        List<String> imagePaths = new ArrayList<>();
        if(isVal(dataString.replace("/profile", RuoYiConfig.getProfile()))){
            String url = dataString.replace("/profile", RuoYiConfig.getProfile());
            try{
                String project = "/profile";
                String sub  = "detect";
                List<String> predicts = ProcessUtils.runPythonScript(url.replace(project, RuoYiConfig.getProfile()),project.replace("/profile", RuoYiConfig.getProfile()),sub);
                List<WorkOrder> workOrderList = new ArrayList<>();
                List<Cover> coverList = new ArrayList<>();
                for(String item: predicts){
                    WorkOrder workOrder = new WorkOrder();
                    String[] sList = item.split(" ");
                    String s = sList[2];
                    int x = s.lastIndexOf(":");
                    imagePaths.add(s.substring(0,x));

                    int last = s.lastIndexOf("\\");
                    String name2 = s.substring(last + 1);
                    last = name2.lastIndexOf(".");
                    int id = Integer.parseInt(name2.substring(0, last));
                    Cover cover = new Cover();
                    cover.setImage(project+"/"+sub+"/"+name2.replace(":",""));
                    cover.setId((long) id);
                    coverList.add(cover);

                    workOrder.setCoverId((long) id);
                    workOrder.setOrderType(0);
                    workOrder.setImage(s.replace(RuoYiConfig.getProfile(), "/profile"));
                    workOrder.setOrderStatus(0L);
                    workOrder.setPriority(3);

                    if(item.contains("no detections")){
                        workOrder.setOrderDesc("请人工排查问题");
                    }else{
                        String[] list = item.split(" ");
                        if(!list[4].equals("0") && list[0].equals("image")){
                            workOrder.setImage(project+"/"+sub+"/"+name2.replace(":",""));
                            if(list[5].equals("lose")){
                                workOrder.setOrderDesc("检测到井盖丢失");
                                workOrder.setPriority(1);
                            }else if(list[5].equals("break")){
                                workOrder.setOrderDesc("检测到井盖破损");
                                workOrder.setPriority(2);
                            }else if(list[5].equals("uncovered")){
                                workOrder.setOrderDesc("检测到井盖未盖");
                                workOrder.setPriority(3);
                            }
                        }
                    }
                    workOrder.setIsDeleted(0);
                    workOrderList.add(workOrder);
                }
                workOrderMapper.insertWorkOrderBatch(workOrderList);
                coverMapper.updateBatchById(coverList);

                for (String imagePath : imagePaths) {
                    try {
                        Path path = Paths.get(imagePath);
                        Files.delete(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    private boolean isVal(String dataString){

        File directory = new File(dataString);

        if (!directory.exists()) {
            return false;
        }

        if (!directory.isDirectory()) {
            return false;
        }

        File[] files = directory.listFiles();

        if (files == null || files.length == 0) {
            return false;
        }

        return true;
    }
}
